package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    //登录
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1 参数校验
        if (dto==null || StringUtils.isBlank( dto.getName() )
                || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 执行查询
        // 根据用户名精确查询有效的用户
//        LambdaQueryWrapper wrapper = new LambdaQueryWrapper();
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName,dto.getName())
                .eq(AdUser::getStatus, AdminConstants.AD_USER_ISSTATUS)
            );
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST );
        }
        // 比对密码
        // 数据库密码 c666c45e7506247eeecbfe2fbaf09e9a
        String dbPwd = adUser.getPassword();

        String password = dto.getPassword();
        String salt = adUser.getSalt();
        // 加密规则： password+salt
        String saltPwd = password + salt;
        String digestPwd = DigestUtils.md5DigestAsHex(saltPwd.getBytes());
        if (!dbPwd.equals(digestPwd)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NAMEORPWD_ERROR );
        }

        //3 更新数据库登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);

        //4 返回结果
        // 生成Token
        Map<String, Object> resultMap = new HashMap<>();
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        resultMap.put("token", token);

        // 用户信息
        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user", adUser);

        return ResponseResult.okResult(resultMap);
    }

}
